package org.example.util;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@Component
public class OssUtils {

    @Autowired
    private OssProperties ossProperties;

    public String getExtension(String fileName) {
        if (fileName == null || !fileName.contains(".")) {
            return ".jpg";
        }else {
            return fileName.substring(fileName.lastIndexOf("."));
        }
    }

    public String upload(MultipartFile file) throws IOException {
        OSS oss = new OSSClientBuilder().build(ossProperties.getEndpoint(),
                ossProperties.getAccessKeyId(), ossProperties.getAccessKeySecret());
        String newFileName = UUID.randomUUID() + getExtension(file.getOriginalFilename());
        oss.putObject(ossProperties.getBucketName(),newFileName,file.getInputStream());
        oss.shutdown();
        return "https://" + ossProperties.getBucketName() + "." +
                ossProperties.getEndpoint() + "/" + newFileName;
    }
}
